package com.rech.xbexpress3;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rech.utils.OtherUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * Created by sunshine on 2020/9/4
 */
public class Jj2NewActivity extends AppCompatActivity {
    private int jjcount = 100;
    private Timer countTimer;
    private TextView djs ;
    private final Handler mHideHandler = new Handler();
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    private String boxValue = "[{}]";
    private TextView tv_jj;
    private TextView tv_jj_cainiao;
    private EditText et_jjm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        setContentView(R.layout.activity_jj2_new);
        djs = findViewById(R.id.jj2_djs);
        mVisible = true;
        getSupportActionBar().hide();
        new FetchGetBoxStateTask().execute();

        countTimer=new Timer();
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                Message message = new Message();
                message.what=20000;
                EventBus.getDefault().post(message);
                if(jjcount < 1){
                    //OtherUtil.restartApplication(Jj2Activity.this);
                    Exit();
                    finish();
                }
            }
        },0,1000);

        Button jj2_back = (Button) findViewById(R.id.jj2_back);
        jj2_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Exit();
                finish();
            }
        });

        tv_jj = (TextView) findViewById(R.id.textView4);
        tv_jj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int mExpType = 0;
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putInt("jj_exp",mExpType);
                editor.putString("jj_boxvalue",boxValue);
                editor.apply();
                Intent intent = new Intent();
                intent.putExtra("isFromWX", false);
                setResult(1002, intent);
                Exit();
                finish();
            }
        });

        tv_jj_cainiao = (TextView) findViewById(R.id.textView3);
        tv_jj_cainiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int mExpType = 2;
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putInt("jj_exp",mExpType);
                editor.putString("jj_boxvalue",boxValue);
                editor.apply();

                Intent intent = new Intent();
                intent.putExtra("isFromCainiao", true);
                setResult(1004, intent);
                Exit();
                finish();
            }
        });

        ImageView gzh_qrcode = (ImageView)findViewById(R.id.gzh_qrcode);
        String cnImage     =  sharedPreferences.getString("CabinetType_gzh","");
        new FetchUrlImageTask(cnImage,gzh_qrcode).execute();

        et_jjm = (EditText)findViewById(R.id.et_jjm);
        et_jjm.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().trim().length() == 6) {
                    new PostByCodeTask(editable.toString().trim()).execute();
                }
            }
        });
    }

    private void Exit(){
        countTimer.cancel();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 10106:
                handleBoxStateTask(message.obj);
                break;
            case 10107:
                Toast.makeText(Jj2NewActivity.this, "获取柜子状态失败", Toast.LENGTH_SHORT).show();
                break;
            case 20000:
                handleDJS();
                break;
            case 10205:
                Toast.makeText(Jj2NewActivity.this, "寄件失败请重试", Toast.LENGTH_SHORT).show();
                et_jjm.setText("");
                break;
            case 10204:
                handleJJTask(message.obj);
                et_jjm.setText("");
                break;

        }
    }

    private void handleJJTask(Object  obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("jj_sjr_address",result.getJSONObject("data").getString("receiver"));
                editor.putString("jj_jjr_address",result.getJSONObject("data").getString("sender"));
                editor.putString("jj_wx_orderId",result.getJSONObject("data").getString("orderId"));

                int mExpType = 0;
                editor.putInt("jj_exp",mExpType);
                editor.putString("jj_boxvalue",boxValue);
                editor.apply();
                Intent intent = new Intent();
                intent.putExtra("isFromWX", true);

                setResult(1002, intent);
                Exit();
                finish();
            }else{

                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle("寄件码错误，请重新输入");
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);
            }

        }catch(Exception e){
            View cv = getWindow().getDecorView();
            AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
            adbuilder.setTitle("网络异常");
            adbuilder.setMessage("2秒后自动关闭！");
            adbuilder.setCancelable(true);
            final AlertDialog dlg = adbuilder.create();
            dlg.show();
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    dlg.dismiss();
                    t.cancel();
                }
            }, 2000);
        }
    }
    
    private void handleDJS(){
        djs.setText(String.valueOf(jjcount));
    }
    public void handleBoxStateTask(Object obj) {
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                JSONArray orders = result.getJSONArray("data");
                boxValue = orders.toString();
                for(int i=0; i<orders.length(); i++){
                    JSONObject jsonObject1 = orders.getJSONObject(i);
                    String itemId = jsonObject1.get("id").toString();
                    String itemName = jsonObject1.get("name").toString();
                    String itemType = jsonObject1.get("type").toString();
                    String itemCount = jsonObject1.get("count").toString();

                    String nameId = "jj2_name"+String.valueOf(i+1);
                    String countId = "jj2_count"+String.valueOf(i+1);
                    String layoutId = "jj2_box"+String.valueOf(i+1);
                    ((TextView)findViewById(OtherUtil.getResId(nameId,R.id.class))).setText(itemName);
                    ((TextView)findViewById(OtherUtil.getResId(countId,R.id.class))).setText(itemCount);
                    findViewById(OtherUtil.getResId(layoutId,R.id.class)).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));


                }


            }
        }
        catch (Exception e){
            Log.d("Grid",e.toString());
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;
    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
}
